﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using System.Reflection;
using NHibernate.Criterion;
using br.nrtech.restaurante.dao.Model;

namespace br.nrtech.restaurante.dao
{
    public static class nhHelper
    {
        public static ICriteria criaCriterios(Object obj)
        {
            PropertyInfo[] arrayPropertyInfo = obj.GetType().GetProperties();
            ICriteria criterio = Sessions.getSession().CreateCriteria(obj.GetType());
            for (int index = 0; index < arrayPropertyInfo.Length; index++)
            {                
                if (arrayPropertyInfo[index].GetValue(obj, null) != null && 
                    arrayPropertyInfo[index].GetValue(obj, null).ToString() != "0")
                {
                    if (!arrayPropertyInfo[index].GetValue(obj, null).GetType().ToString().Contains("Collection"))
                        criterio.Add(Restrictions.Eq(arrayPropertyInfo[index].Name, arrayPropertyInfo[index].GetValue(obj, null)));
                }
            }
            return criterio;
        }

        public static System.Collections.IList getWithFilter(Object objRef)
        {
           ICriteria criterio = criaCriterios(objRef);
           return criterio.List();
        }

        public static System.Collections.IList getAll(Object objRef)
        {
            ICriteria criterio = Sessions.getSession().CreateCriteria(objRef.GetType());
            return criterio.List();
        }

        public static void insert(Object objRef)
        {
            Sessions.getSession().SaveOrUpdate(objRef);
        }

        public static void update(Object objRef)
        {
            Sessions.getSession().Update(objRef);
        }

        public static void delete(Object objRef)
        {
            Sessions.getSession().Delete(objRef);
        }

    }
}
